<template>
  <div class="tui-checkbox-container">
    <label :for="id" class="tui-checkbox-label">
      <input
        type="checkbox"
        :id="id"
        :name="name"
        :checked="modelValue"
        :disabled="disabled"
        :required="required"
        class="tui-checkbox"
        @change="handleChange"
        @focus="handleFocus"
        @blur="handleBlur"
      />
      <span v-if="label" class="tui-checkbox-text">{{ label }}</span>
    </label>
    <p v-if="errorMessage" class="tui-checkbox-error">{{ errorMessage }}</p>
  </div>
</template>

<script lang="ts" setup>

import type { TuiCheckboxProps } from './types';

// 定义组件props
const props = withDefaults(defineProps<TuiCheckboxProps>(), {
  id: '',
  name: '',
  modelValue: false,
  label: '',
  disabled: false,
  required: false,
  errorMessage: '',
});

// 定义emits
const emit = defineEmits<{
  (e: 'update:modelValue', value: boolean): void;
  (e: 'change', event: Event): void;
  (e: 'focus', event: FocusEvent): void;
  (e: 'blur', event: FocusEvent): void;
}>();

// 处理变化事件
const handleChange = (event: Event) => {
  const target = event.target as HTMLInputElement;
  const checked = target.checked;
  emit('update:modelValue', checked);
  emit('change', event);
};

// 处理聚焦事件
const handleFocus = (event: FocusEvent) => {
  emit('focus', event);
};

// 处理失焦事件
const handleBlur = (event: FocusEvent) => {
  emit('blur', event);
};
</script>

<style scoped>
.tui-checkbox-container {
  display: flex;
  align-items: center;
}

.tui-checkbox-label {
  display: flex;
  align-items: center;
  cursor: pointer;
  user-select: none;
}

.tui-checkbox {
  width: 16px;
  height: 16px;
  margin-right: 8px;
  accent-color: var(--tui-color-primary);
}

.tui-checkbox:disabled {
  cursor: not-allowed;
  opacity: 0.5;
}

.tui-checkbox-text {
  font-size: 14px;
}

.tui-checkbox-error {
  color: var(--tui-color-danger);
  font-size: 12px;
  margin-top: 4px;
  margin-bottom: 0;
  margin-left: 24px;
}
</style>